<template>
	<view class="nav-section">
		<!-- 地图 -->
		<map class="map" ref="mapRef" id="examMap" :include-points="allPoints" :scale="mapSite.scale" :enableZoom="true"
			:enableScrollWheel="true" :enableRotate="true" :enable-scroll="true" :enableOverlooking="true" :latitude="mapSite.latitude"
			:longitude="mapSite.longitude" :markers="markers" :polyline="polyline" @loaded="handleMapLoaded"
			@markertap="handleMarkerTap" @labeltap="handleMarkerTap"></map>
	</view>
</template>

<script setup>
	import {
		ref,
		nextTick,
		watch,
		reactive,
		onUnmounted,
		onMounted
	} from 'vue';
	const emits = defineEmits(['update', 'onClickMarker']);
	const mapRef = ref(null);
	// 腾讯地图API配置
	const MAP_KEY = 'X3CBZ-5VJ6G-S3OQQ-QLMR4-2Y6HO-Q5FS7'; // 需申请真实key
	const API_BASE = 'https://apis.map.qq.com/ws/direction/v1';
	const props = defineProps({
		examInfo: {
			type: Object,
			default: () => {}
		},
		// 添加停车位数据属性
		parkingSpots: {
			type: Array,
			default: () => []
		}
	});
	const mapSite = reactive({
		latitude: 0,
		longitude: 0,
		scale: 14
	})
	const markers = ref([]);
	const polyline = ref([]); // 路线数据
	const allPoints = ref([]);
	import {
		useStore
	} from '@/ya/store';
	const getLocation = async () => {
		// WGS84（GPS原始）: 39.908722, 116.397497
		// GCJ02（腾讯/高德）: 39.908722, 116.403873
		// BD09（百度）: 39.915071, 116.403927
		const {
			userLocation: {
				latitude,
				longitude
			}
		} = useStore('user');
		mapSite.latitude = latitude;
		mapSite.longitude = longitude;
		console.log('mapSite：', mapSite);
		// 先增加标记
		addMaker(mapSite);
		// adjustMapView();
	};
	// 生成停车位标记
	const generateParkingMarkers = (spots) => {
		console.log('generateParkingMarkers', spots)
		return spots.map(spot => {
			let tempIcon;
			let x;
			let y;
			if (spot.number >= 5) {
				tempIcon = '/static/site10+.png';
				x = -8
				y = -32
			} else if (spot.number < 5 && spot.number != 0) {
				tempIcon = '/static/site10-.png'
				x = -4
				y = -32
			} else {
				tempIcon = '/static/site0.png'
				x = -4
				y = -32
			}
			const marker = ({
				id: spot.id,
				latitude: spot.latitude,
				longitude: spot.longitude,
				width: 40,
				height: 40,
				// 使用背景圆圈图标，可根据状态切换不同颜色 iconPath: ''
				iconPath: tempIcon,
				// 添加停车位编号标签
				label: {
					content: spot.number,
					color: '#333',
					fontSize: 14,
					x: x, // 水平居中（相对于图标宽度的50%）
					y: y, // 垂直向上偏移（图标高度的一半，当前图标高度40px）
					anchorX: x, // 文字锚点水平居中
					anchorY: y, // 文字锚点底部对齐（使文字底部与偏移位置对齐）
					zIndex: 20 // 标签层级高于图标
				}
			})
			console.log('生成标记:', marker); // 添加调试日志
			return marker;
		});
	};
	const updateParking = (newSpots) =>{
		// 保留用户位置标记，添加停车位标记
		const parkingMarkers = generateParkingMarkers(newSpots);
		markers.value = [...markers.value.filter(m => m.id < 100), ...parkingMarkers];
		// 调整地图视野以包含所有标记
		allPoints.value = markers.value.map(m => ({
			latitude: m.latitude,
			longitude: m.longitude
		}));
	};
	// 地图打点
	const addMaker = (location) => {
		markers.value.push({
			id: 0,
			latitude: location.latitude,
			longitude: location.longitude,
			width: 50,
			height: 50,
			iconPath: '/static/user-location.png'
		});
		console.log('markers', markers.value);
	};
	// 修改地图视野调整方法
	const adjustMapView = () => {
		// allPoints.value = results.length > 0 ?
		// 	results.flatMap(r => processRouteData(r, '').points) : [mapSite, {
		// 		latitude: props.examInfo.kdy,
		// 		longitude: props.examInfo.kdx
		// 	}];

		nextTick(() => {
			// 改用回调方式创建地图上下文
			const mapContext = uni.createMapContext('examMap', this);
			// 添加延迟确保地图渲染完成
			setTimeout(() => {
				// 改用回调方式获取区域
				mapContext.getRegion({
					success: (res) => {
						const latDelta = res.northeastLatitude - res.southwestLatitude;
						const lngDelta = res.northeastLongitude - res.southwestLongitude;
						const scale = Math.min(18, Math.max(14, 17 - Math.max(latDelta,
							lngDelta) * 100));
						console.log('scale', scale);
						// 直接更新响应式数据
						mapSite.scale = scale;
						// 调整视野包含所有路径点
						mapContext.includePoints({
							points: allPoints.value,
							padding: [80, 80, 80, 80]
						});
					},
					fail: (err) => {
						console.error('获取地图区域失败:', err);
					}
				});
			}, 800); // 增加800ms延迟确保地图完成渲染
		});
	};
	// 新增地图加载完成处理
	const handleMapLoaded = () => {
		console.log('地图初始化完成')
		mapSite.scale = 16 // 设置更高的初始缩放级别
	}
	const handleMarkerTap = (e) => {
		// e.markerId 是被点击的标记点的 id
		console.log('点击了标记点，markerId:', e.markerId);
		emits('onClickMarker', e);
	}
	// 地图API请求方法
	const requestRoute = async (mode, startLat, startLng) => {
		console.log('from:', startLat, startLng)
		console.log('to:', `${props.examInfo.kdy},${props.examInfo.kdx}`)
		const url = `${API_BASE}/${mode}/`;
		const response = await uni.request({
			url,
			data: {
				from: `${startLat},${startLng}`,
				to: `${props.examInfo.kdy},${props.examInfo.kdx}`,
				key: MAP_KEY
			}
		});
		if (response.data.status !== 0) {
			throw new Error('API请求失败');
		}
		console.log("腾讯地图路线规划：", response.data.result);
		return response.data.result;
	};

	// 路线数据处理方法
	const processRouteData = (result, color) => {
		if (!result?.routes?.[0]?.polyline) return {
			points: [],
			color
		};

		// 坐标解压逻辑（前向差分）
		const coors = [...result.routes[0].polyline];
		for (let i = 2; i < coors.length; i++) {
			coors[i] = coors[i - 2] + coors[i] / 1000000;
		}

		// 转换为纬度经度对象数组
		const points = [];
		for (let i = 0; i < coors.length; i += 2) {
			points.push({
				latitude: coors[i],
				longitude: coors[i + 1]
			});
		}

		return {
			points,
			color,
			width: 6,
			arrowLine: true
		};
	};
	const startBackgroundLocation = async () => {
		await uni.startLocationUpdate({
			success: res => console.log('开启应用接收位置消息成功'),
			fail: err => console.error('开启应用接收位置消息失败：', err)
		});

		// 添加位置监听（需确保在页面卸载时移除）
		const locationListener = uni.onLocationChange(location => {
			console.log('examMap监听到：', location);
			if (location?.latitude && location.latitude != 0) {
				useStore('user').updateLocation(location);
				getLocation(); // 更新地图显示
			}
		});

		// 添加平台条件编译
		// #ifdef MP-WEIXIN
		uni.startLocationUpdateBackground({
			success: () => console.log('后台定位已开启'),
			fail: (err) => {
				uni.showToast({
					title: '后台定位失败,请确认是否开启！',
					icon: 'none'
				});
				console.error(err);
			}
		});
		// #endif

		// 添加卸载时清理逻辑
		return () => {
			uni.offLocationChange(locationListener);
			uni.stopLocationUpdate();
		}

	};
	onMounted(async () => {
		// uni.getSetting({
		// 	success: (res) => {
		// 		if (!res.authSetting['scope.userLocationBackground']) {
		// 			uni.showModal({
		// 				title: '需要后台定位权限',
		// 				content: '请允许小程序在使用期间和离开后获取位置',
		// 				success: (res) => {
		// 					if (res.confirm) {
		// 						uni.openSetting(); // 跳转至权限设置页
		// 					}
		// 				}
		// 			});
		// 		} else {
		// 			startBackgroundLocation();
		// 		}
		// 	}
		// });
	});
	//  监听地图位置变化
	watch(
		() => mapSite,
		async () => {
			await nextTick();
			await useStore('user').getLocation();
			await getLocation();
		}, {
			deep: true,
			immediate: true
		}
	);
	// 监听停车位数据变化
	watch(() => props.parkingSpots, (newSpots) => {
		console.log('watch', newSpots)
		if (newSpots.length) {
			updateParking(newSpots);
		}
	}, {
		deep: true,
		immediate: true
	});
	onUnmounted(() => {
		// 页面卸载时停止定位
		if (typeof uni !== 'undefined' && uni.stopLocationUpdate) {
			uni.stopLocationUpdate();
		}
	});
</script>

<style lang="scss">
	.nav-section {
		height: 100vh;
		width: 100%;
		border-radius: 8px;
		overflow: hidden;
		.map {
			width: 100%;
			height: 100%;
		}
	}
</style>